#include "MinLengthSubs.h"


/* C'tor:
 */
MinLengthSubs::MinLengthSubs() :
		subs_map(new MultiMap())
{
}

MinLengthSubs::~MinLengthSubs()
{
	// delete the positions vector
	for (MultiMap::iterator it = subs_map->begin(); it != subs_map->end(); it++)
	{
		MultiMapValues &val = it->second;
		delete val.positions;
	}
	// delete the map itself
	delete subs_map;
}

void MinLengthSubs::addSubstring(SubStr sub, size_t pos)
{
	vector<uint> *cur_positions = innerGetSubstringPositions(sub);
	if (cur_positions == NULL)
	{
		// first time we encounter that substring
		vector<uint> *positions = new vector<uint>();
		positions->push_back(pos);
		MultiMapValues new_val(sub, positions);
		subs_map->insert(MultiMapElement(sub, new_val));
	}
	else
	{
		// the key is already there, need to update the dynamic bitset
		cur_positions->push_back(pos);
	}

}

/* Retrieves the positions of the given substring.
 * If the substring isn't found, returns NULL.
 */
const vector<uint>* MinLengthSubs::getSubstringPositions(SubStr sub) const
{
	pair<MultiMap::const_iterator, MultiMap::const_iterator> ret = subs_map->equal_range(sub);
	for (MultiMap::const_iterator it = ret.first; it != ret.second; it++)
	{
		MultiMapValues val = it->second;
		if (val.sub == sub)
			return val.positions;
	}
	return NULL;

}


vector<uint>* MinLengthSubs::innerGetSubstringPositions(SubStr sub)
{
	pair<MultiMap::iterator, MultiMap::iterator> ret = subs_map->equal_range(sub);
	for (MultiMap::iterator it = ret.first; it != ret.second; it++)
	{
		MultiMapValues val = it->second;
		if (val.sub == sub)
			return val.positions;
	}
	return NULL;
}



#ifdef DEBUG

#include "WindowReader.h"
#include <iostream>
using namespace std;

void MinLengthSubs::print() const
{
	cout << "Printing MinLengthSubs hash-table:" << endl;
	for (MultiMap::const_iterator it = subs_map->begin(); it != subs_map->end(); it++)
	{
		MultiMapValues val = it->second;
		cout << "\tKey = ";
		WindowReader window(val.sub);
		window.printStr();
		cout << endl << "\t";
		for (vector<uint>::const_iterator it = val.positions->begin(); it != val.positions->end(); it++)
			cout << *it << ", ";
///		val.bitset->printBitset();
		cout << endl;
	}
}
#endif /* DEBUG */

